<template>
  <div class="apply-form">
    <!-- tab栏 -->
    <el-tabs v-model="activeTab" type="card">
      <!-- ====== 基本信息 ====== -->
      <el-tab-pane label="基本信息" name="base">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="老人姓名" prop="name">
            <el-input v-model="form.name" maxlength="10" show-word-limit placeholder="请输入老人姓名" />
          </el-form-item>

          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="form.idCard"
              maxlength="18"
              show-word-limit
              placeholder="请输入身份证号"
              @blur="handleIdCardBlur"
            />
          </el-form-item>

          <el-form-item label="性别">
            <el-radio-group v-model="form.gender">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="出生日期">
            <el-input v-model="form.birth" placeholder="出生日期" disabled />
          </el-form-item>

          <el-form-item label="年龄">
            <el-input v-model="form.age" placeholder="年龄" disabled />
          </el-form-item>

          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="form.phone" maxlength="11" show-word-limit placeholder="请输入手机号" />
          </el-form-item>

          <el-form-item label="家庭住址" prop="address">
            <el-input v-model="form.address" maxlength="100" show-word-limit placeholder="请输入家庭住址" />
          </el-form-item>

          <!-- 下拉项 -->
          <el-form-item label="民族">
            <el-select v-model="form.nation" placeholder="请选择民族">
              <el-option v-for="item in nationList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="政治面貌">
            <el-select v-model="form.political" placeholder="请选择政治面貌">
              <el-option v-for="item in politicalList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="宗教信仰">
            <el-select v-model="form.religion" placeholder="请选择宗教信仰">
              <el-option v-for="item in religionList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="婚姻状况">
            <el-select v-model="form.marital" placeholder="请选择婚姻状况">
              <el-option v-for="item in maritalList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="文化程度">
            <el-select v-model="form.education" placeholder="请选择文化程度">
              <el-option v-for="item in educationList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="经济来源">
            <el-select v-model="form.income" placeholder="请选择经济来源">
              <el-option v-for="item in incomeList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="医疗保障">
            <el-select v-model="form.insurance" placeholder="请选择医疗保障">
              <el-option v-for="item in insuranceList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>

          <el-form-item label="特长爱好">
            <el-input v-model="form.hobby" maxlength="20" show-word-limit placeholder="请输入特长爱好" />
          </el-form-item>

          <el-form-item label="医保卡号">
            <el-input v-model="form.medicalCard" maxlength="19" show-word-limit placeholder="请输入医保卡号" />
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- ====== 家庭信息 ====== -->
      <el-tab-pane label="家庭信息" name="family">
        <el-table :data="form.familyList" border style="width: 100%">
          <el-table-column label="家庭成员名" prop="name">
            <template #default="{ row }">
              <el-input v-model="row.name" placeholder="请输入" />
            </template>
          </el-table-column>
          <el-table-column label="联系方式" prop="phone">
            <template #default="{ row }">
              <el-input v-model="row.phone" maxlength="11" placeholder="请输入手机号" />
            </template>
          </el-table-column>
          <el-table-column label="与老人关系" prop="relation">
            <template #default="{ row }">
              <el-select v-model="row.relation" placeholder="请选择">
                <el-option v-for="item in relationList" :key="item" :label="item" :value="item" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ $index }">
              <el-button icon="Minus" circle size="small" type="danger" @click="removeRow($index)" />
              <el-button 
                v-if="$index === form.familyList.length - 1" 
                icon="Plus" 
                circle size="small" 
                type="primary" 
                @click="addRow" 
              />
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- ====== 资料上传 ====== -->
      <el-tab-pane label="资料上传" name="upload">
        <div class="upload-notice mb-4 text-gray-500">
          图片大小不超过2M，仅支持 PNG / JPG / JPEG 类型
        </div>

        <el-form ref="uploadForm" :model="form" label-width="120px">
          <!-- 一寸照片 - 存储到extend1 -->
          <el-form-item label="一寸照片">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="headers"
              list-type="picture-card"
              :limit="1"
              :on-success="(response, file) => handleUploadSuccess(response, file, 'photo')"
              :on-error="handleUploadError"
              :file-list="photoFileList"
            >
              <el-icon><Plus /></el-icon>
              <template #file="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
              </template>
            </el-upload>
          </el-form-item>

          <!-- 身份证人像面 - 存储到idCardFront -->
          <el-form-item label="身份证人像面">
            <el-upload
              :action="uploadUrl"
              :headers="headers"
              list-type="picture-card"
              :limit="1"
              :on-success="(response, file) => handleUploadSuccess(response, file, 'idCardFront')"
              :on-error="handleUploadError"
              :file-list="idCardFrontFileList"
            >
              <el-icon><Plus /></el-icon>
              <template #file="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
              </template>
            </el-upload>
          </el-form-item>

          <!-- 身份证国徽面 - 存储到idCardBack -->
          <el-form-item label="身份证国徽面">
            <el-upload
              :action="uploadUrl"
              :headers="headers"
              list-type="picture-card"
              :limit="1"
              :on-success="(response, file) => handleUploadSuccess(response, file, 'idCardBack')"
              :on-error="handleUploadError"
              :file-list="idCardBackFileList"
            >
              <el-icon><Plus /></el-icon>
              <template #file="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <!-- 底部操作按钮（居中） -->
    <div class="form-footer">
      <el-button @click="handleReturn">返回</el-button>
      <el-button
        type="primary"
        @click="handleAction"
      >
        {{ isLastTab ? '提交' : '保存' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth' // 假设从auth工具中获取token
import{createElder} from '@/api/checkInApply/checkInApply'


// 允许向父组件同步表单数据 & 控制流程
const emit = defineEmits(['nextStep', 'return', 'update-form'])
const activeTab = ref('base')

// 上传配置
const uploadUrl = "http://localhost:8080/common/upload";
const headers = { Authorization: "Bearer " + getToken() };

// 表单数据（保留你原来的字段）
const form = reactive({
  name: '', idCard: '', gender: '', birth: '', age: '',
  phone: '', address: '', nation: '', political: '', religion: '',
  marital: '', education: '', income: '', insurance: '',
  hobby: '', medicalCard: '',
  // 图片存储字段
  idCardFront: '',  // 身份证正面
  idCardBack: '',   // 身份证反面
  photo: '',      // 一寸照片（扩展字段）
  familyList: [{ name: '', phone: '', relation: '' }]
})

// 上传文件列表管理（用于控制 el-upload 的 file-list）
const photoFileList = ref([])    // 一寸照片文件列表
const idCardFrontFileList = ref([]) // 身份证正面文件列表
const idCardBackFileList = ref([])  // 身份证反面文件列表

const tabs = ['base', 'family', 'upload']
const isLastTab = computed(() => activeTab.value === tabs[tabs.length - 1])

const formRef = ref(null)
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^\d{17}[\dXx]$/, message: '身份证格式错误', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入家庭住址', trigger: 'blur' }]
}

const nationList = ['汉族', '回族', '壮族', '苗族', '满族']
const politicalList = ['群众', '中共党员', '预备党员', '其他']
const religionList = ['佛教', '道教', '基督教', '伊斯兰教', '无']
const maritalList = ['已婚', '未婚', '丧偶', '离婚']
const educationList = ['小学', '初中', '高中', '本科', '硕士', '博士']
const incomeList = ['退休金', '政府补助', '家庭资助']
const insuranceList = ['职工医保', '居民医保']
const relationList = ['子女', '配偶', '亲属', '朋友']

// 身份证解析：解析出生日期、性别并计算年龄
const handleIdCardBlur = () => {
  const id = form.idCard
  if (!/^\d{17}[\dXx]$/.test(id)) return

  const birth = id.substring(6, 14)
  const birthYear = parseInt(birth.substring(0, 4))
  const birthMonth = parseInt(birth.substring(4, 6))
  const birthDay = parseInt(birth.substring(6, 8))

  form.birth = `${birthYear}-${birthMonth.toString().padStart(2, '0')}-${birthDay.toString().padStart(2, '0')}`

  form.gender = parseInt(id.charAt(16)) % 2 === 1 ? '男' : '女'

  const today = new Date()
  const currentYear = today.getFullYear()
  let age = currentYear - birthYear
  const currentMonth = today.getMonth() + 1
  if (currentMonth < birthMonth || (currentMonth === birthMonth && today.getDate() < birthDay)) {
    age--
  }
  form.age = age
}

// 家庭信息操作
const addRow = () => {
  form.familyList.push({ name: '', phone: '', relation: '' })
}

const removeRow = (i) => {
  if (form.familyList.length <= 1) {
    ElMessage.warning('至少保留1位家庭成员信息')
    return
  }
  form.familyList.splice(i, 1)
}

// 上传成功处理
const handleUploadSuccess = (response, file, field) => {
  // 假设后端返回格式 { code: 200, data: { url: '图片地址' } }
  if (response.code === 200) {
    form[field] = response.url  // 将图片地址保存到对应字段
    ElMessage.success('上传成功')

    // ✅ 立即向父组件同步该字段（防止父组件验证时拿不到）
    emit('update-form', { [field]: form[field] })

    // 更新文件列表显示
    if (field === 'photo') {
      photoFileList.value = [{ ...file, url: response.data.url }]
    } else if (field === 'idCardFront') {
      idCardFrontFileList.value = [{ ...file, url: response.data.url }]
    } else if (field === 'idCardBack') {
      idCardBackFileList.value = [{ ...file, url: response.data.url }]
    }
  } else {
    ElMessage.error('上传失败: ' + (response.msg || '未知错误'))
  }
}

// 上传失败处理
const handleUploadError = (err) => {
  console.error('上传错误:', err)
  ElMessage.error('上传失败，请重试')
}

// 返回按钮
const handleReturn = () => {
  const idx = tabs.indexOf(activeTab.value)
  if (idx === 0) {
    emit('return') // 第一个 tab 触发父组件 return
  } else {
    activeTab.value = tabs[idx - 1] // 其他 tab 返回上一个 tab
  }
}

// 保存/提交按钮（保留你原来的行为：base->family->upload->submit）
const handleAction = async () => {
  if (isLastTab.value) {
    if (!validateUpload()) return

    try {
      const res = await createElder(form)
      if (res.code === 200) {
        ElMessage.success('提交成功')
        emit('nextStep', form)
      } else {
        ElMessage.error(res.msg || '提交失败')
      }
    } catch (err) {
      console.error(err)
      ElMessage.error('提交失败，请重试')
    }
    return
  }

  // 其它 tab 保存逻辑保持不变
  if (activeTab.value === 'base') {
    formRef.value.validate(valid => {
      if (!valid) return
      ElMessage.success('保存成功')
      emit('update-form', { ...form })
      activeTab.value = tabs[1]
    })
  } else if (activeTab.value === 'family') {
    if (!validateFamily()) return
    ElMessage.success('保存成功')
    emit('update-form', { ...form })
    activeTab.value = tabs[2]
  }
}

// 校验家庭成员
const validateFamily = () => {
  for (let i = 0; i < form.familyList.length; i++) {
    const f = form.familyList[i]
    if (!f.name || !f.phone || !f.relation) {
      ElMessage.warning(`家庭成员第 ${i + 1} 行信息不完整`)
      return false
    }
    if (!/^1[3-9]\d{9}$/.test(f.phone)) {
      ElMessage.warning(`家庭成员第 ${i + 1} 行手机号格式错误`)
      return false
    }
  }
  return true
}

// 校验上传文件
const validateUpload = () => {
  if (!form.photo) {
    ElMessage.warning('请上传一寸照片')
    return false
  }
  if (!form.idCardFront) {
    ElMessage.warning('请上传身份证人像面')
    return false
  }
  if (!form.idCardBack) {
    ElMessage.warning('请上传身份证国徽面')
    return false
  }
  return true
}
</script>

<style scoped>
.apply-form {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}
.form-footer {
  margin-top: 30px;
  text-align: center;
}
.upload-notice {
  color: #606266;
  font-size: 14px;
}
:deep(.el-upload-list__item) {
  width: 148px;
  height: 148px;
}
</style>
